const Config = require('cordova-config');
const fs = require('fs');
let xml2js = require('xml2js');
let Client = require('ssh2-sftp-client');
const sd = require('silly-datetime');
const path = require('path');
const shell = require('child_process');
const ROOT_DIR = path.resolve(__dirname, '../');
const config = new Config(path.join(ROOT_DIR, 'config.xml'));

let argv1 = process.argv[2] || 'test';//是第三个参数执行命令运行：node .\utils\build.js jlhs

let apkPath = "";
let jsonPath = "";
let outputFileName = argv1 + '-' + sd.format(new Date(), 'YYYY-MM-DD HHmmss') + '.apk';
let server_apk_url = 'http://59.172.6.149:25100/release/test/app/apk/qcfw/' + outputFileName;
// let server_apk_url = 'http://59.172.6.149:25100/release/test/app/apk/qcfw/' + argv1 + '/' + outputFileName;


task()
.then(readConfig);
// .then(buildAPK)
//   .then(copyAPK)
//   .then(updateXml);


//读取配置 并修改 config.xml 文件
function readConfig() {
  return new Promise((resolve, reject) => {
    const build_json = JSON.parse(fs.readFileSync('utils/build.json'));
    const json = build_json[argv1];
    let name = json['name'] || build_json['default-name'];
    let version = json['version'] || build_json['default-version'];
    let prefix = build_json['package-prefix'];
    let suffix = json['package-suffix'];
    let package = suffix ? prefix + '.' + suffix : prefix;
    config.setName(name);
    config.setID(package);
    config.setVersion(version);
    config.writeSync();
    resolve();
  })
}

//执行打包
function buildAPK() {
  return new Promise((resolve, reject) => {
    let workerProcess = shell.exec('cordova build android --release');
    workerProcess.stdout.on('data', (data) => console.log(data));
    workerProcess.stderr.on('data', (data) => console.log(data));
    workerProcess.on('close', (code) => resolve());
  });
}

//复制文件到push目录
function copyAPK() {
  return new Promise((resolve, reject) => {
    let apk_src = path.join(ROOT_DIR, 'platforms/android/app/build/outputs/apk/armv7/release/app-armv7-release.apk');
    let json_src = path.join(ROOT_DIR, 'platforms/android/app/build/outputs/apk/armv7/release/output.json');
    let dest = path.join(ROOT_DIR, 'push');
    if (!fs.existsSync(dest)) fs.mkdirSync(dest);

    let apk_fileName = outputFileName;
    let json_fileName = argv1 + '-' + sd.format(new Date(), 'YYYY-MM-DD HHmmss') + '.json';

    apkPath = path.join(dest, apk_fileName);
    jsonPath = path.join(dest, json_fileName);

    fs.copyFileSync(apk_src, apkPath);
    console.log(apkPath);
    fs.copyFileSync(json_src, jsonPath);
    console.log(jsonPath);
    resolve();
  })
}

/**
 * 修改app-update 的xml 文件
 */
function updateXml(callback) {
  return new Promise((resolve, reject) => {
    console.log('开始更新xml配置');

    let content = fs.readFileSync(jsonPath);
    content = JSON.parse(content)[0];
    let versionCode = content['apkInfo']['versionCode'];

    let xmlParser = new xml2js.Parser({explicitArray: false, ignoreAttrs: true}); // xml -> json
    let jsonBuilder = new xml2js.Builder(); // xml -> json

    let xmlFilePath = path.join(ROOT_DIR, 'other/' + argv1 + '.xml');
    let xml = fs.readFileSync(xmlFilePath);

    xmlParser.parseString(xml, function (err, result) {
      result['update']['version'] = versionCode;
      result['update']['url'] = server_apk_url;
      let json2xml = jsonBuilder.buildObject(result);
      fs.writeFileSync(xmlFilePath, json2xml);
      console.log('update.xml 文件 更新成功');
      resolve();
    });
  })
}


/**
 * 上传
 * @param callback
 */
function upload() {
  return new Promise((resolve, reject) => {
    console.log("start upload apk.")
    let sftp = new Client();

    task()
      .then(createClient)
      .then(uploadXml)
      .then(uploadApk)
      .then(closeClient)
      .then(resolve)

    function createClient() {
      return new Promise((resolve, reject) => {
        sftp.connect({
          host: '59.172.6.149',
          port: '15122',
          username: 'jlsoft',
          password: 'F0088AjH7GLk'
        }).then(s => {
          resolve()
        });
      });
    }

    function uploadXml() {
      return new Promise((resolve, reject) => {
        sftp.put(xmlFilePath, '/home/jlsoft/web/nginx/html/release/test/app/config/' + xmlFileName)
          .then(s => {
            console.log("xml upload success.", s);
            resolve();
          });
      });
    }

    function uploadApk(callback1) {
      return new Promise((resolve, reject) => {
        sftp.put(outputFilePath, '/home/jlsoft/web/nginx/html/release/test/app/apk/qcfw' + outputFileName)
        //  sftp.put(outputFilePath, '/home/jlsoft/web/nginx/html/release/test/app/apk/' + projectName + outputFileName)
          .then(s => {
            console.log("apk upload success.", s);
            resolve()
          });
      });
    }

    function closeClient(callback1) {
      return new Promise((resolve, reject) => {
        sftp.end().then(s => {
          resolve()
        });
      });
    }
  });
}

function task() {
  return new Promise((resolve, reject) => {
    resolve();
  })
}


